package com.ziyucoding.springboot.labs.lab4.concurrentdemo.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * CyclicBarrier 示例3
 *
 * @author ziyucoding
 * @date 2022-10-27
 **/
@Slf4j
public class CyclicBarrierExample3 {

    private static CyclicBarrier barrier = new CyclicBarrier(3, () -> {
        // 线程到达屏障，优先执行
        log.info("callback is running");
    });

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            final int num = i;
            Thread.sleep(1000);
            executorService.execute(() -> {
                try {
                    test(num);
                } catch (Exception e) {
                    log.error("发生异常", e);
                }
            });
        }
        log.info("finish");
        executorService.shutdown();
    }

    /**
     * 测试
     *
     * @param num
     * @return void
     **/
    private static void test(int num) throws InterruptedException, BrokenBarrierException {
        Thread.sleep(1000);
        log.info("{} is ready", num);
        barrier.await();
        log.info("{} continue", num);
    }
}
